package org.mullin.stratego.server;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mullin.stratego.shared.Player;

import com.google.appengine.api.channel.ChannelPresence;
import com.google.appengine.api.channel.ChannelService;
import com.google.appengine.api.channel.ChannelServiceFactory;

import static com.googlecode.objectify.ObjectifyService.ofy;

public class ChannelConnectServlet extends HttpServlet {
	private ChannelService channelService = ChannelServiceFactory.getChannelService();
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
		ChannelPresence presence = channelService.parsePresence(req);
		
		Player p = ofy().load().type(Player.class).id(presence.clientId()).now();
		if (null == p) {
			p = new Player(presence.clientId(), 1);
		} else {
			p.addConnection();
		}
		
		ofy().save().entity(p).now();
	}
}
